/*
 * Copyright 2002-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.security.web.context;

import java.io.IOException;
import java.util.function.Supplier;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;

/**
 * A {@link jakarta.servlet.Filter} that uses the {@link SecurityContextRepository} to
 * obtain the {@link SecurityContext} and set it on the {@link SecurityContextHolder}.
 * This is similar to {@link SecurityContextPersistenceFilter} except that the
 * {@link SecurityContextRepository#saveContext(SecurityContext, HttpServletRequest, HttpServletResponse)}
 * must be explicitly invoked to save the {@link SecurityContext}. This improves the
 * efficiency and provides better flexibility by allowing different authentication
 * mechanisms to choose individually if authentication should be persisted.
 * 该Filter是用于存储用户认证信息的
 * @author Rob Winch
 * @author Marcus da Coregio
 * @since 5.7
 */
public class SecurityContextHolderFilter extends GenericFilterBean {

	private static final String FILTER_APPLIED = SecurityContextHolderFilter.class.getName() + ".APPLIED";
	// SecurityContextRepository接口 提供一种在整个请求上下文存储SecurityContext的能力
	// 该属性默认为DelegatingSecurityContextRepository，DelegatingSecurityContextRepository也是实现SecurityContextRepository接口的一个代理类
	// DelegatingSecurityContextRepository允许代理多个SecurityContextRepository来实现SecurityContext的存储
	// DelegatingSecurityContextRepository对loadContext和saveContext进行了实现
	private final SecurityContextRepository securityContextRepository;
	// 在线程中存储SecurityContext的策略  默认都是ThreadLocal。
	private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
		.getContextHolderStrategy();

	/**
	 * Creates a new instance.
	 * @param securityContextRepository the repository to use. Cannot be null.
	 */
	public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository) {
		Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
		this.securityContextRepository = securityContextRepository;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
	}

	private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		// 如果已经执行过 该过滤器
		if (request.getAttribute(FILTER_APPLIED) != null) {
			// 跳过 直接执行下一个过滤器
			chain.doFilter(request, response);
			return;
		}
		// 标记该过滤器在本次请求过程中已经执行过
		request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
		// 从SecurityContextRepository获取到SecurityContext
		Supplier<SecurityContext> deferredContext = this.securityContextRepository.loadDeferredContext(request);
		try {
			// 将SecurityContext存储到securityContextHolderStrategy中，也就是存储到线程中。 需要注意的是此处只是将获取securityContext的lambda表达式方法存到了
			// contextHolder中，并没有真正获取到securityContext，因为此时的securityContext还并没有存储到session或者request中，所以此处方法叫延迟设置context
			// 再后面的认证过程中会将securityContext存储到session或者request，再AnonymousAuthenticationFilter过滤器中会获取该lambda表达式进一步封装，再AuthorizationFilter
			// 过滤器中会使用该lambda表达式获取用户信息进行认证处理
			this.securityContextHolderStrategy.setDeferredContext(deferredContext);
			// 继续执行Filter
			chain.doFilter(request, response);
		}
		finally {
			// 代码执行到此处 后续所有的Filter都已执行完后，又回到当前Filter中 请求执行完成后，清除SecurityContext
			this.securityContextHolderStrategy.clearContext();
			// 移除已执行标记
			request.removeAttribute(FILTER_APPLIED);
		}
	}

	/**
	 * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
	 * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
	 *
	 * @since 5.8
	 */
	public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
		Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
		this.securityContextHolderStrategy = securityContextHolderStrategy;
	}

}
